package com.hirsi.core.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hirsi.core.thread.UploadThread;

import java.io.File;
import java.io.IOException;

public class TorrentUtil {

    private static String TORRENT_PATH = "/config/mktorrent_s2";

    static {
        if (System.getProperty("os.name").contains("Windows")) TORRENT_PATH = "D:\\WinRAR\\Rar.exe";
        else {
            if (!FileUtil.exist(TORRENT_PATH)) FileUtil.writeFromStream(RarUtil.class.getResourceAsStream("/mktorrent_s2"), TORRENT_PATH);
        }
    }

    public static void init() {}

    public static void create(String path) {

        new Thread(() -> {
            try {
                Boolean success = false;
                String _path = path;
                String substring = _path.substring(_path.lastIndexOf("/") + 1);
                if (substring.contains(" ")) _path = _path.replace(substring, "'" + substring + "'");
                System.out.println(_path);
                String[] cmd = new String[]{"sh", "-c", TORRENT_PATH + " " + _path};
                Process exec = Runtime.getRuntime().exec(cmd, null, new File("/config"));
                exec.waitFor();
                String name = String.format("%s.torrent", path.substring(path.lastIndexOf("/") + 1));
                File file = new File("/config/" + name);
                if (file.exists()) {
                    System.out.println("种子文件制作完成：" + file.getPath());
                    String remotePath = UploadThread.TARGET_PATH + name;
                    String targetPath = UploadThread.TARGET_PATH;
                    JSONObject jsonObject = BaiduDiskUtil.preCreate(remotePath, targetPath, file.length());
                    if (jsonObject.getInt("errno") == 0) {
                        String uploadid = jsonObject.getStr("uploadid");
                        jsonObject = BaiduDiskUtil.superFile2(remotePath, uploadid, 0, file);
                        if (jsonObject.containsKey("partseq") && jsonObject.getInt("partseq").equals(0)) {
                            jsonObject = BaiduDiskUtil.createFile(remotePath, file.length(), uploadid, targetPath, String.format("[\"%s\"]", jsonObject.getStr("md5")));
                            if (jsonObject.getInt("errno") == 0) success = true;
                        }
                    }
                }
                if (success) System.out.println("种子文件已上传");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
